package com.xrz.sxm.aj.db;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.xrz.sxm.aj.activity.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class DBManager {
	/**
	 * 数据库版本号 升级的时候需要把这个版本号 +1
	 */
	private static final int DB_VERSON = 8;
	private final int BUFFER_SIZE = 400000;
	public static final String DB_NAME = "aj.db"; // 保存的数据库文件名
	public static final String PACKAGE_NAME = "com.xrz.sxm.aj.activity";
	public static final String DB_PATH = "/data"
			+ Environment.getDataDirectory().getAbsolutePath() + "/"
			+ PACKAGE_NAME; // 在手机里存放数据库的位置

	private Context context;

	public DBManager(Context context) {
		this.context = context;
	}

	private SharedPreferences getPreferences() {
		return context.getSharedPreferences("dbversion", 0);
	}

	private void setRunning() {
		getPreferences().edit().putInt("config", 1).commit();
	}

	private boolean isFirstRunning() {
		return getPreferences().getInt("config", 0) == 0;
	}

	private SQLiteDatabase sqLiteDatabase;

	public synchronized SQLiteDatabase getDB() {
		if (sqLiteDatabase == null || sqLiteDatabase.isOpen() == false)
			sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(DB_PATH + "/" + DB_NAME,
					null);
		return sqLiteDatabase;
	}
	public synchronized  void closeDB(){
		if (sqLiteDatabase != null)
			sqLiteDatabase.close();
	}


	public static String getDir() {
		return DB_PATH;
	}

	public static String getName() {
		return DB_NAME;
	}

	public void copy() {
		try {
			File file = new File(DB_PATH + "/" + DB_NAME);
			if (isFirstRunning()) {
				file.delete();
				Log.e("DBManager", "db start update");
			}
			if (!(file.exists())) {// 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
				boolean a = file.createNewFile();
				InputStream is = this.context.getResources().openRawResource(
						R.raw.aj); // 欲导入的数据库
				FileOutputStream fos = new FileOutputStream(
						file.getAbsolutePath());
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
				Log.e("DBManager", "db update over");
				setRunning();
			}
		} catch (Exception e) {
			Log.e("Database", "File not found");
			e.printStackTrace();
		}
	}
}